package com.zeroes.cons;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;


import org.zeroes.common_prelude.*;
import org.zeroes.Events.*;
import org.zeroes.Components.*;
import org.zeroes.svg.*;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;


import playn.text.*;
import playn.text.Font.Style;
import playn.text.TextFormat.Alignment;
import playn.text.TextFormat.Effect;
import android.graphics.Color;
import android.graphics.Path;
import android.graphics.PathMeasure;
public class MyGame extends ZSGame {
	private World w;
	private Body ball;
	private ZSSprite s,sigla,ss2;
	public ZSLabel txt;
	private ZSGroup g;
private int xx=0,yy=0;
public boolean once=false;
private ZSTexture2D  txttxt;
private ZSBatchLayer tal,BB ;
private ZSLayer _BB;
public vector2 lt=new vector2(0,0);
private float ssx=1,ssy=1,lty;
String dir="fata";
	public MyGame(){
	super();
	this.updateRate=0;
	}
	
public MyGame(ZSGameOptions go){
	super(go);
	
	
}
	
	public void initialize(){
		
		
		super.initialize();
	//	SoundEngine.sharedEngine().preloadEffect(this.ctx, R.raw.airshot3);
		SoundEngine.sharedEngine().playSound(ctx, R.raw.background_music_aac, true);
		
w = new World(new Vector2(0f,-9.0f),false);
BodyDef groundBodyDef = new BodyDef();    
groundBodyDef.position.set(0, 0);
groundBodyDef.type = BodyDef.BodyType.StaticBody;
Body groundBody = w.createBody(groundBodyDef);
PolygonShape groundBox = new PolygonShape();
FixtureDef boxShapeDef = new FixtureDef();
boxShapeDef.shape=groundBox;
groundBox.setAsEdge(new Vector2(0,0), new Vector2(width/32.0f, 0));
groundBody.createFixture(boxShapeDef);
groundBox.setAsEdge(new Vector2(0,0), new Vector2(0, height/32.0f));
groundBody.createFixture(boxShapeDef);
groundBox.setAsEdge(new Vector2(0,height/32.0f), new Vector2(width/32.0f, height/32.0f));
groundBody.createFixture(boxShapeDef);
groundBox.setAsEdge(new Vector2(width/32.0f,height/32.0f), new Vector2(width/32.0f, 0));
groundBody.createFixture(boxShapeDef);

sigla=$("sigla");
BodyDef ballBodyDef = new BodyDef(); 
ballBodyDef.type=BodyDef.BodyType.DynamicBody;
ballBodyDef.position.set(sigla.position.x/32.0f,(height-sigla.position.y)/32.0f);
ball=w.createBody(ballBodyDef);

CircleShape circle=new CircleShape();
circle.setRadius(56.0f/32.0f) ;
PolygonShape pshape =new PolygonShape();
pshape.setAsBox(2.0f, 2.0f);
FixtureDef ballShapeDef = new FixtureDef();
ballShapeDef.shape = circle;
ballShapeDef.density = 1.0f;
ballShapeDef.friction = 0.3f;
ballShapeDef.restitution = 0.7f;
ball.createFixture(ballShapeDef);

/*		int[] clr = {214,200,145};
ZSColoredQuad cq = new ZSColoredQuad("cq",Color.MAGENTA,CGSize.make(128.0f, 128.0f));
this._BB=this.getLayerByTitle("Background");
_BB.addSprite(cq);
cq.setPosition(500, 300);*/
		//txttxt= new ZSTexture2D("Narcisescu","Verdana",48.0f);
		
		
		//ZSTexture2D txttxt0= new ZSTexture2D();
		//AndroidFont af= new AndroidFont(null,Style.ITALIC,36);
		
		//TextFormat tf = new TextFormat(af,80,Alignment.LEFT, Color.MAGENTA, Effect.NONE);
	//	txttxt0.drawFormatedText("Narcis", tf);
	/*	txt = new ZSLabel("Narcis",Style.ITALIC,36,Color.BLUE,100.0f);
txt.tag="";
this._BB=this.getLayerByTitle("Background");
_BB.addSprite(txt);
txt.setPosition(500, 300);
txt.data("I:h", new ZSSingle<Integer>(13));*/

		//this.buildCollisionEventFor("text","scorimage");
		



		E.on("sys.EndLevel.*", new Callback(){
			public void run(String p, ZSEvent e){

			//	Toast.makeText(ctx, "LOADING ... PLEASE WAIT!", Toast.LENGTH_LONG).show();
				ZSGameOptions gameoptions = new ZSGameOptions(ZSGameManager.GAME_TYPE_SVG_WITH_JAVASCRIPT);

				        gameoptions.setJSSource("eve.js");
				        gameoptions.setSVGResource(R.raw.test3);
				       //gameoptions.autoAdjustToScreenSize=false;
				        gameoptions.useAccelerometer=false;
				        Level2 newgame = new Level2(gameoptions);
				    
				        ZSGameManager.AskMe().changeGameTo(newgame);
			
			
			}
		});
	//	this.swapLayers(0, 1);
	
//s.setScale(2, 2);
//	g=s.Group();
	//$("sigla").Group().layer.anchorX=0;
//	$("sigla").Group().layer.anchorY=0;
	//g.anchorX=1;
//	g.anchorY=1;
	//g.setGroupRotation(45);
		/*s=new ZSSprite(R.raw.construct2);
		s.setPosition(128, 128);
		 s.setScale(0.3f,0.3f);
	  
		 ZSSprite s1 = new ZSSprite("image3809");
		scene.add(s);
		scene.add(s1);*/
		
	/*	ZSTexture2D tex = new ZSTexture2D(ctx.getResources().openRawResource(R.raw.construct2));
		ZSBatchLayer bl = new ZSBatchLayer("B",this,tex);
		
		this.addLayer(bl);
		bl.addRect(new Rect(0,0,128,128,"rotita"));
		bl.addRect(new Rect(128,0,256,128,"_rotita"));
		this._BB=this.getLayerByTitle("Background");
		ZSSprite ss = new ZSSprite("r1",bl.rectById("rotita"));
		ZSSprite ss1 = new ZSSprite("r2",bl.rectById("_rotita"));
		bl.addSprite(ss);
		bl.addSprite(ss1);
		ss.setPosition(64, 64);
		ss1.setPosition(500, 64);

		ss2.setScale(1, 1);
		
		ZSSprite cs = tal.cloneSprite(ss2, "cloneSS2");
		cs.setPosition(100, 400);*/
		s=$("lvlimage");	
		g=s.Group();
		g.translate(200, 0);
		//s.updateBlend(ZSEffect.SOURCE_STOP);
	//	Log.v("gtrans", "numar : "+s.Idata("numar"));
		/*tal = (ZSBatchLayer)this.getLayerByTitle("ANIM");
		ss2 = new ZSSprite("w0",tal.rectById("w0"));
		tal.addSprite(ss2);
		ss2.setPosition(150, 300);*/
		
		/*SVGElement poteca = this.domparser.getPathById("poteca");
		float pl = SVGElement.getPathLength(SVGElement.getPathFromString(poteca.pathData));
		
		
		float[] pos = SVGElement.getPathPositionAtLength(SVGElement.getPathFromString(poteca.pathData), 900.0f);
		s.setPosition(pos[0], pos[1]);
		float _r  = (float) (Math.atan2(pos[2],pos[3])*180/Math.PI);
		Log.v("gtrans", "Lungime cale : "+pl +" rot "+_r);
		s.setRotation(_r);*/
		//tal = (ZSBatchLayer)this.getLayerByTitle("TA");
		//ZSBMoveTo mt = new ZSBMoveTo("",s,14,15,16);
	//mt._("run", PARAM.$());
		E.on("*.Accelerometer.*", new Callback(){
			
			public void run(String p, ZSEvent e){
				ZSPair<?,?> r =(ZSPair<?,?>) e.who;
				Vertex3 v3 = e.castToVertex3(r);
				w.setGravity(new Vector2(v3.y*15,-v3.x*15));
			}
		});
	}
	
	public void update(float dt){
		super.update(dt);
		w.step(dt/1000, 8, 3);
		
	//	Log.v("gtrans", "ball pos :  "+ball.getPosition().x*32+" , "+ball.getPosition().y*32);
		sigla.setPosition(ball.getPosition().x*32, height-ball.getPosition().y*32);
		sigla.setRotation(Util.to_degrees(ball.getAngle()));
		w.clearForces();
		//g.rotateClockwise(4);
	//	s.rotateClockwise(7);
	//g.layer.rotateClockwise(2);
	//	tal.rotateClockwise(1);
	//	$("sigla").Group().layer.rotateClockwise(4);
		//scene.get(1).rotateCounterClockwise(6);
		if(dir=="fata")
		{
			xx+=1;
			if(xx>400){
				dir="spate";
			}
		}
		else
		{
			xx-=1;
			if(xx<-400){
				dir="fata";
			}
		}
		//Log.v("gtrans", "Valoare xx :  "+xx);
		//s.setPosition(xx, yy);
		//g.layer.translate(xx, 0);
		
		//g.translate(xx, 0);
		//g.gsx+=0.00001*xx;
		//g.gsy+=0.00001*xx;
		ssx-=0.000005*xx;
		ssy-=0.000005*xx;
	//	g.layer.setScale(ssx, ssy);
		//$("sigla").Group().layer.rotateClockwise(1);
		//s.setScale(ssx, ssy);
	//	g.markTransformDirty();
		//g.gcx+=xx;
		if(once){
		ZSGame gg = (ZSGame)ZSGameManager.AskMe().forCurrentGame();
		gg.initialize();	
		once=false;
		}
		
			/*	ZSGameOptions gameoptions = new ZSGameOptions(ZSGameManager.GAME_TYPE_SVG_WITH_JAVASCRIPT);
				ZSGameOptions gameoptions = new ZSGameOptions(ZSGameManager.GAME_TYPE_ALL_PURE_JAVA);
		        gameoptions.setJSSource("eve.js");
		        gameoptions.setSVGResource(R.raw.test2);
		        gameoptions.useAccelerometer=false;
		        ZSGameManager.AskMe().forCurrentGame().clearAll();
		       // ZSGameManager.AskMe().toStop();
		     //ZSGameManager.AskMe().nullifyGame();
		       
		        ZSGame newgame = new ZSGame(gameoptions);
		        ZSGameManager.AskMe().toRun(newgame);
		        newgame.initialize();
			
		}
			/*ZSTexture2D txttxt1= new ZSTexture2D();
			AndroidFont af= new AndroidFont(null,Style.BOLD,36);
			
			TextFormat tf = new TextFormat(af,80,Alignment.LEFT, Color.MAGENTA, Effect.NONE);
			txttxt1.drawFormatedText("Petru", tf);

			txt.newTexture(txttxt1);
		}*/
		
		
	}
	
	public void onTouch(){

	//	ZSGameManager.AskMe().resumeCurrentGame();
	/*	txt.newText("Petrutzu");
		txt.newWidthWrap(200.0f);
		txt.newColor(Color.GREEN);*/
		//txt.visit();
	//	SoundEngine.sharedEngine().playEffect(ctx, R.raw.airshot3);
		
		/*ZSTexture2D txttxt1= new ZSTexture2D();
		AndroidFont af= new AndroidFont(null,Style.BOLD,36);
		
		TextFormat tf = new TextFormat(af,80,Alignment.LEFT, Color.MAGENTA, Effect.NONE);
		txttxt1.drawFormatedText("Petru", tf);*/
		//ZSTexture2D txttxt= new ZSTexture2D("Brindusescu","Verdana",124.0f);
		
		//txttxt.initWithText("Brindusescu", "Tahoma", 36.0f);
		//txt.newTexture(txttxt1);
		//txt = new ZSSprite(txttxt);
		//Log.v("gtrans", "draw from sprite");
		//ss2.changeRect(tal.rectById("w5"));
/*E.makeCustomInterval(1000, 16,2, "sprite.animation.play", new Condback(){
			
			public void is(String evName, int idx){
				ZSEvent ev = new ZSEvent(evName,null,idx);
				E._(evName, ev);
				Log.v("gtrans", "frame : "+idx);
			}
});*/
		
		/* COmponents*/
	/*	ZSLUParameters params = new ZSLUParameters();
		//params.Add("", new ZSSingle<ZSSprite>(s));
		params.AddZSSpriteParam("", s);
		ZSLogicUnit u = new ZSLogicUnit(){
			
			
			public void is(ZSComponent c,ZSLUParameters p){
				//ZSSprite _p=(ZSSprite)p.getParamAtIndex(0).getFirst();
				ZSSprite _p=p.getZSSpriteParamAtIndex(0);
				//c.AddProperty("*.property.id", new ZSSingle<String>("Narciselu ..."));
				c.AddStringProperty("*.property.id", "Narciselu");
				
				ZSLogicUnit act = new ZSLogicUnit(){
					public void is(ZSComponent _c,ZSLUParameters _p){
						Log.v("gtrans", "From fun action with love ...");
						//_p.Result(new ZSSingle<String>("FUN!!!!"));
						_p.StringResult("FUNNNNNN ");
						}
				};
				c.AddAction("*.action.fun", act);
				Log.v("gtrans", "Component constructor " + _p.tag+" "+c.name +ZSGameManager.AskMe().events.getSizeofSheet());
			}
		};
		
		ZSComponent comp = new ZSComponent("test",params,u);
	//	comp.setProperty("id", new ZSSingle<String>("Petrutzu ..."));
		comp.setStringProperty("id", "Petrutzu ..");
		Log.v("gtrans", "Valoare proprietate id "+comp.getStringProperty("id"));
		String f=comp._S("fun",params);
		Log.v("gtrans", "Valoare intoaarsa de actiunea fun :  "+f);
		
		sf componenet
		*/
		//ZSSpriteBehavior beh = new ZSSpriteBehavior(s);
		//ZSBMoveTo mt = new ZSBMoveTo(s,2000,14,15,16);
		//mt._("run", null);
		//Log.v("gtrans", "sprite behav tag :  "+beh.getSpriteProperty("Subject").tag);
		//super.onTouch();
			/*E.makeOnce("Sys.touch.down", new Condback(){
			
			public void is(String evName, int idx){
				if(lty>240){
				ZSPair<vector2,String> poz = new ZSPair<vector2,String> (lt,""); 
				ZSEvent ev = new ZSEvent(evName,poz,0);
				E._(evName, ev);
				}
			}
		});*/
	
		//ss2.newRect(tal.rectById("scor"));
	//	Log.v("ZConstructoidActivity", " cx , cy >>>"+s.Group().gcx+" , "+s.Group().gcy );
		//sigla=$("sigla");
		//ZSLayer sl=this.getLayerByTitle("Foreground");
		//sl.translate(800, 0);
		//sl.removeGroup(g);
		//g.setOpacity(0.5f);
		//sl.moveSpriteintoGroupAndLayer(sigla,"freeEntities", "TA");
		//once=false;
		
		//this.getLayerByTitle("Background").removeSprite(s);
	//	this.getLayerByTitle("Background").hide();
		//g.hide();
		//g.setGroupRotation(g.rotation+45);
		//g.gsx-=0.1f;
	//	g.gsy-=0.1f;
		//g.markTransformDirty();
	   // s.setPosition((int)ltx, (int)lty);
		/*if(s.getZ()==1)
	s.setZOrder(-1);
		else
	s.setZOrder(1);
		
		this.makeReorderingDirty();*/
	

	}

}
